﻿using System;
using System.Globalization;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using Fuse8.ContentManagementFramework.Domain;
using Fuse8.DomainFramework.Common.Locator;

namespace Fuse8.ContentManagementFramework.Administration.Attributes
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class AdminCurrentCultureAttribute : AuthorizeAttribute
    {
        public AdminCurrentCultureAttribute()
        {
            Roles = "*";
            Users = "*";
        }

        protected override bool AuthorizeCore(HttpContextBase filterContext)
        {
            CultureInfo locale = CultureInfo.CurrentCulture;
            var user = DependencyServiceLocator.Current.GetInstance<ICmsContext>().ContextUser;
            if (filterContext.Request.QueryString["clear"] == "true")
            {
                HttpContext.Current.Session["CMS:CurrentLocale"] = null;
            }
            if (!string.IsNullOrEmpty(filterContext.Request.QueryString["locale"]))
            {
                locale = new CultureInfo(filterContext.Request.QueryString["locale"]);
                if (filterContext.Request.QueryString["no"] != "true")
                {
                    HttpContext.Current.Session["CMS:CurrentLocale"] = locale.Name;
                }
            }
            else if (HttpContext.Current.Session["CMS:CurrentLocale"] != null)
            {
                locale = new CultureInfo(HttpContext.Current.Session["CMS:CurrentLocale"].ToString());
            }
            else if (user != null && !(user is CmsAnonimousUser) && !string.IsNullOrEmpty(user.Locale))
            {
                locale = new CultureInfo(user.Locale);
            }
            else
            {
                var langs = filterContext.Request.UserLanguages;
                if (langs != null && langs.Length > 0)
                {
                    locale = new CultureInfo(langs[0]);
                }
            }

            Thread.CurrentThread.CurrentUICulture = locale;

            return true;
        }
    }
}